// pages/square/public2.js
const app = getApp();
var topOpacity = 0;
var util = require('../../utils/util.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "发起组局", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: ''
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    publicContent: "",
    time: '选择时间',
    timeList: [],
    images: [], //上传图片集合
    isHeightModeArr: [],
    numList: [],
    numId: 0,
    limitNum: '选择人数',
    title: '',
    partPro: '',
    role: false,

    authData: {
      authType: '0', //0表示使用登录弹窗  1表示使用完善昵称头像弹窗 2表示直接弹出头像昵称选择框
      authUsername: "false", //是否已经授权头像昵称
    },
    showLogin: false, //是否显示授权弹窗
    showWsInfoDom: false, //直接显示头像昵称弹窗
    showPrivacyFlag: app.globalData.showPrivacyFlag,
    showPrivacy: false,

    openid: '',
    shareImg: '',
    shareTitle: '',
    is_nickAndHead: 0,
    sendImgArr: [], //提交数据时的图片
    imgMax: 0, //上传图片的大小限制M
    multiArray: [], //大分类数组
    smallCateList: [], //小分类数组
    multiIndex: [0, 0], //用户选项大分类&小分类
  },
  // 初始化第二列数据
  initSecondColumnData: function () {
    var that = this;
    this.setData({
      'multiArray[1]': that.data.smallCateList[0]
    });
  },

  // 选择改变事件
  bindMultiPickerChange: function (e) {
    console.log('picker发送选择改变，携带值为', e.detail.value);
    this.setData({
      multiIndex: e.detail.value
    });
  },
  // 选择列变化事件
  bindMultiPickerColumnChange: function (e) {
    var that = this;
    console.log('修改的列为', e.detail.column, '，值为', e.detail.value);
    //判断是否是选择的提示
    if (e.detail.value == 0 && e.detail.column == 0) {
      that.setData({
        'multiArray[1]': []
      });
      return;
    }
    if (e.detail.column === 0) {
      // 第一列变化时，动态更新第二列数据
      this.setData({
        'multiArray[1]': that.data.smallCateList[e.detail.value - 1]
      });
    }
  },
  role() {
    let that = this;
    that.setData({
      role: !that.data.role
    })
  },
  bindTextAreaBlur: function (e) {
    this.setData({
      publicContent: e.detail.value
    })
  },
  //选择截止日期
  // onPickerChange(e) {
  //   let that = this;
  //   console.log(e)
  //   that.setData({
  //     time: e.detail
  //   });
  //   var time = util.formatTime(new Date());
  //   console.log(time < e.detail.value)
  //   if (time > e.detail.value) {
  //     app.showTip("截止时间不能小于当前时间");
  //   }
  // },
  timeChange(e) {
    let that = this;
    that.setData({
      time: that.data.timeList[e.detail.value].time
    })
  },
  //选择人数限制
  numChange(e) {
    let that = this;
    that.setData({
      limitNum: that.data.numList[e.detail.value].num,
      numId: e.detail.value
    })
  },
  //标题输入框
  titleIpt(e) {
    var title = e.detail.value;
    this.setData({
      title: title
    })
  },
  //描述输入框
  partPro: function (e) {
    let value = e.detail.value.replace(/\n/g, '<br/>');
    this.setData({
      partPro: value
    })
  },

  //处理完善信息
  addWxInfo() {
    this.setData({
      ['authData.authType']: 1,
      showLogin: true
    });
  },

  //接收子组件电话授权及头像昵称授权后后返回的值
  returnVal(e) {
    var that = this;
    //授权完头像昵称
    this.setData({
      is_nickAndHead: 1
    });

    app.showTip('个人信息已完善');
  },

  //发起组局 数据判断
  createPart() {
    let that = this;

    //判断是否授权过头像昵称了
    if (that.data.is_nickAndHead == 0) {
      that.addWxInfo();
      return;
    }

    let title = that.data.title;
    let partPro = that.data.partPro;
    let images = that.data.images;
    let time = that.data.time;
    let limitNum = that.data.limitNum;
    let bigCate = that.data.multiArray[0][that.data.multiIndex[0]];
    let smallCate = that.data.multiArray[1][that.data.multiIndex[1]];
    if (that.data.multiIndex[0] == 0) {
      app.showTip("请选择组局类别");
      return;
    }
    if (title == "") {
      app.showTip("请输入标题");
      return;
    }
    if (partPro == "") {
      app.showTip("请输入描述");
      return;
    }
    if (images.length == 0) {
      app.showTip("请至少上传一张照片");
      return;
    }
    if (time == "" || time == '选择时间') {
      app.showTip("请选择截止时间");
      return;
    }
    if (limitNum == "" || limitNum == '选择人数') {
      app.showTip("请选择限制人数");
      return;
    }

    //提交附件
    that.sendFj();
  },


  //将附件保存至服务器
  sendFj() {
    var  that=this;
    that.uploadImgHandle(0);
  },

  //上传图片
  uploadImgHandle(row){
    var that = this;
    wx.showLoading({
      title: '信息发布中...'
    });

       wx.uploadFile({
        url: that.data.baseUrl + "uploadsGame.php", //服务器接口
        method: 'POST',
        filePath: that.data.images[row],
        header: {
          'content-type': 'multipart/form-data'
        },
        name: 'file', //服务器定义的Key值
        formData: {},
        success: function (res) {
          //wx.hideLoading();
          console.log(res.data);
          if (res.data) {
            var sendImgArr = that.data.sendImgArr;
            sendImgArr.push(res.data);
            that.setData({
              sendImgArr: sendImgArr
            });

            if (that.data.images.length == that.data.sendImgArr.length) {
              //调用最终上传数据
              wx.hideLoading();
              that.sub();
            }else{
              that.uploadImgHandle(row+1);
            }
          } else {
            app.showTip('服务器保存图片失败,请刷新页面重试');
          }
        },
        fail: function () {
          wx.hideLoading();
          app.showTip('服务器繁忙,请稍候重试');
        }
      });
  },

  //提交组局数据到后端数据库
  sub() {
    var that = this;
    wx.showLoading({
      title: '信息发布中...'
    });

    let role = that.data.role;
    if (role) {
      role = 1;
    } else {
      role = 0;
    }

    wx.request({
      url: that.data.baseUrl + 'addGame.php',
      method: 'POST',
      data: {
        'openid': that.data.openid,
        'title': that.data.title,
        'game_desc': that.data.partPro,
        'is_yz_bm': role,
        'bm_end_time': that.data.time,
        'max_people': that.data.limitNum,
        'imgArr': JSON.stringify(that.data.sendImgArr),
        'bigCate': that.data.multiArray[0][that.data.multiIndex[0]],
        'smallCate': that.data.multiArray[1][that.data.multiIndex[1]]
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          app.showTip(res.data['msg']);
          setTimeout(function () {
            //缓存麓客局
            wx.setStorageSync('listType', 1);
            wx.switchTab({
              url: '/pages/square/index'
            });
          }, 1500);
        } else {
          app.showTip(res.data['msg']);
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },


  //上传图片
  upLoadImg: function (e) {
    let that = this;

    //判断是否同意了引导协议
    if (app.globalData.showPrivacyFlag == false) {
      that.setData({
        showPrivacy: true
      })
      return;
    }

    wx.chooseImage({
      count: 10 - that.data.images.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        let tempFilePaths = res.tempFilePaths;
        console.log(tempFilePaths)
        let images = that.data.images;
        let isHeightModeArr = that.data.isHeightModeArr;
        if ((images.length + tempFilePaths.length) > 9) {
          app.showTip("最多只能上传9张");
          return;

        }
        for (var item in res.tempFilePaths) {
          that.data.images.push(res.tempFilePaths[item]);
          isHeightModeArr.push(false);
          tempFilePaths = that.data.images;
        }
        //限制上传图片大小为5M,所有图片少于5M才能上传
        let size = res.tempFiles.every(item => {
          return item.size <= parseInt(that.data.imgMax) * 1024 * 1024
        })
        if (size) {
          that.setData({
            images: tempFilePaths,
            isHeightModeArr: isHeightModeArr
          })
        } else {
          app.showTip("上传图片不能大于" + that.data.imgMax + "M哦");

        }
      }
    })
  },

  // 图片加载后判断图片宽高比例
  oneImageLoad(e) {
    const {
      width,
      height,
    } = e.detail
    let index = e.currentTarget.dataset.index;
    console.log("height:" + height + ".....width" + width + "....e:" + e)
    let isHeightModeArr = this.data.isHeightModeArr;
    if (height >= width) {
      isHeightModeArr[index] = true;
      this.setData({
        isHeightModeArr
      })
    }

  },
  //删除图片
  delFile(e) {
    let that = this;
    let delNum = e.currentTarget.dataset.index;
    let images = that.data.images;
    let isHeightModeArr = that.data.isHeightModeArr;
    images.splice(delNum, 1);
    isHeightModeArr.splice(delNum, 1);
    that.setData({
      images: images,
      isHeightModeArr: isHeightModeArr
    })
  },
  // 预览图片
  previewImage(e) {
    let that = this,
      imgsrc = e.currentTarget.dataset.presrc,
      arr = that.data.images
    //console.log(preArr)
    wx.previewImage({
      current: imgsrc,
      urls: arr
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    //that.initSecondColumnData();
    //判断缓存里是否有值
    var headerUrlList = wx.getStorageSync('headerUrlList');
    if (headerUrlList.constructor == Array && headerUrlList.length > 0) {
      //返回中有值
      that.setData({
        ['defaultData.goUrl']: headerUrlList[headerUrlList.length - 1]
      });
    }

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getPublic2PageInfo(res.data.openid);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getPublic2PageInfo(openid);
    }

    //调用分享
    that.getShareInfo();
  },

  getPublic2PageInfo(openid) {
    var that = this;

    wx.showLoading({
      title: '数据加载中...'
    });

    wx.request({
      url: that.data.baseUrl + 'getPublic2PageInfo.php',
      method: 'POST',
      data: {
        openid: openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            is_nickAndHead: res.data.is_nickAndHead,
            imgMax: res.data.imgMax,
            numList: res.data.numList,
            multiArray: res.data.bigCateList,
            smallCateList: res.data.smallCateList,
            timeList:res.data.timeList
          });
        } else {
          //后台请求失败
          app.showTip(res.data.msg);
          return;
        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  //关闭指引
  closeZy() {
    this.setData({
      showPrivacy: false,
      showLogin: false,
      showWsInfoDom: false
    });
  },

  //点击查看协议指引
  handleOpenPrivacyContract() {
    // 打开隐私协议页面
    wx.openPrivacyContract({
      success: () => {}, // 打开成功
      fail: () => {}, // 打开失败
      complete: () => {}
    })
  },

  //点击同意协议
  handleAgreePrivacyAuthorization() {
    this.setData({
      showPrivacy: false,
      showPrivacyFlag: true
    });
    app.globalData.showPrivacyFlag = true;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //更新showPrivacyFlag
    this.setData({
      showPrivacyFlag: app.globalData.showPrivacyFlag
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/square/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})